<template>
    <div class="staff">
      <div class="staff-left">
        <el-input v-model="search" placeholder="Filter keyword" />
  
        <el-tree
          style="max-width: 600px; margin-top: 10px"
          class="filter-tree"
          :data="options1"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </div>
      <div class="staff-right">
        <div
          class="staff-right-top"
          style="display: flex; justify-content: space-between"
        >
          <a-button @click="allNotice">群发通知</a-button>
          <div>
            <a-button type="primary" @click="addDepart">添加员工</a-button>
            <a-button style="margin-left: 5px" @click="exportExcel"
              >excel导出</a-button
            >
            <a-button style="margin-left: 5px" @click="importExcel"
              >excel导入</a-button
            >
  
            <el-dialog
              v-model="uploadDialogVisible"
              title="批量添加数据"
              width="40%"
            >
              <el-form label-width="120px">
                <el-form-item label="文件上传：">
                  <el-upload
                    drag
                    accept=".xls,.xlsx"
                    :auto-upload="false"
                    :on-change="handleChange"
                  >
                    <el-icon class="el-icon--upload">
                      <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        请上传.xls,.xlsx格式文件，文件最大为500kb
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-form>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="uploadDialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="submitUpload">
                    导入
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </div>
        </div>
        <!-- 表格 -->
        <el-table
          ref="multipleTableRef"
          :data="
            filterTableData.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column fixed prop="staffPhoto" label="头像">
            <template #default="scope">
              <img
                :src="scope.row.staffPhoto"
                alt=""
                style="width: 40px; height: 40px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="scope">
              {{ scope.row.formOfEmployment === 1 ? "正式" : "非正式" }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门"></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="180px">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleClick(scope.$index, scope.row)">
                查看
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="rolehandleEdit(scope.row)"
                >角色</el-button
              >
              <el-popconfirm
                confirm-button-text="Yes"
                cancel-button-text="No"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="Are you sure to delete this?"
                @confirm="confirmEvent"
                @cancel="cancelEvent"
                style="color: rgb(77, 164, 255)"
              >
                <template #reference>
                  <el-button
                    link
                    style="color: rgb(77, 164, 255); font-size: 0.78rem"
                    type="prim77, 164, 255ary"
                    size="small"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
  
      <!--  -->
      <el-dialog v-model="detail" :title="title" width="900px">
        <el-form
          ref="ruleFormRef"
          style="max-width: 900px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="ruleForm.username" />
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="ruleForm.workNumber" disabled />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="ruleForm.mobile" />
          </el-form-item>
          <el-form-item label="部门" prop="departmentId">
            <el-cascader
              v-model="ruleForm.departmentId"
              :options="options"
              :props="defaultProps1"
              @change="bumenhandleChange"
            />
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="ruleForm.formOfEmployment" placeholder="请选择">
              <el-option label="正式" :value="1" />
              <el-option label="非正式" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间" required>
            <el-form-item prop="timeOfEntry">
              <el-date-picker
                v-model="ruleForm.timeOfEntry"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item label="转正时间" required>
            <el-form-item prop="correctionTime">
              <el-date-picker
                v-model="ruleForm.correctionTime"
                type="date"
                aria-label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-form-item>
          <el-form-item label="图片上传" prop="img_path">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              @change="uploadfile2"
            >
              <img
                v-if="ruleForm.staffPhoto"
                :src="ruleForm.staffPhoto"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              v-if="ruleForm.id"
            >
              确定
            </el-button>
            <el-button type="primary" @click="submitFormAdd(ruleFormRef)" v-else>
              添加
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
  
      <!-- 分配角色弹窗 -->
      <el-dialog
        v-model="dialogVisibles"
        title="分派角色"
        width="500"
        :before-close="handleClose"
      >
        <div>
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in AllData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-checkbox-group>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisibles = false">取消</el-button>
            <el-button type="primary" @click="roleOK"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 通知消息弹窗 -->
      <el-dialog
        v-model="notice"
        title="群发通知"
        width="500"
        :before-close="noticeNo"
      >
        <div class="flex gap-2">
          <div
            style="border-radius: 20px; border: 1px solid black; padding: 10px"
          >
            <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              style="margin: 4px"
              @close="noticeClose(tag)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
          <el-form-item label="消息等级" style="margin-top: 20px">
            <!-- prop="formOfEmployment" -->
            <el-select v-model="messagedj">
              <el-option label="通知信息" value="1" />
              <el-option label="提示信息" value="2" />
              <el-option label="重要信息" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input
              v-model="content"
              style="width: 100%"
              :autosize="{ minRows: 5, maxRows: 10 }"
              type="textarea"
              placeholder="Please input"
            />
          </el-form-item>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="notice = false">取消</el-button>
            <el-button type="primary" @click="noticeOK"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from "vue";
  import { ElTree } from "element-plus";
  import { ElTable } from "element-plus";
  
  import ExcelJS from "exceljs";
  import FileSaver from "file-saver";
  import { importFile } from "../components/excel";
  import { InfoFilled } from "@element-plus/icons-vue";
  import type { ComponentSize, FormInstance, FormRules } from "element-plus";
  import StaffAPi from "../api/axios";
  import buildMenu from "../components/buildment";
  import {
    getEnableRoleList,
    alertEnabled,
    getNotice,
  } from "../api/axios";
  import {showMessage} from '../api/staff'
  
  interface User {
    title: string;
    stateTime: string;
    endTime: string;
    img: string;
    phone: number;
    id: number;
    bumen: number;
    pinyong: number;
  }
  
  const addDepart = () => {
    title.value = "添加信息";
    detail.value = true;
    ruleForm.value = {};
  };
  const handleEdit = (index: number, row: User) => {
    console.log(index, row);
    roledis.value = true;
    // rolehandleEdit()
    dialogVisibles.value = true;
    // notice.value=true
    // fenFlag.value = true;
  };
  const handleDelete = (index: number, row: User) => {
    console.log(index, row);
    StaffAPi.deldept(row.id).then((res) => {
      console.log(res);
      getData();
    });
  };
  const handleClick = (index: number, row: User) => {
    console.log("click");
    console.log(index, row);
    title.value = "查看信息";
    detail.value = true;
    StaffAPi.getdept(row.id).then((res) => {
      console.log(res);
      ruleForm.value = res.data.data;
    });
  };
  const mass = () => {
    // detail.value = false;
    notice.value = true;
  };
  
  const confirmEvent = () => {
    console.log("confirm!");
  };
  const cancelEvent = () => {
    console.log("cancel!");
  };
  
  // fenye
  const tableData: any = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(1);
  const small = ref(false);
  const background = ref(false);
  const disabled = ref(false);
  
  const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
  };
  const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
  };
  
  const options = ref([]);
  
  const optionsId = ref(0);
  const bumenhandleChange = (value: any) => {
    console.log(value);
    optionsId.value = value[value.length - 1];
    console.log("optionsId.value: ", optionsId.value);
  };
  
  const options1 = ref([]);
  const getData = () => {
    StaffAPi.getData(1, 30, "", ida.value).then((res: any) => {
      console.log(res);
      tableData.value = res.data.data.rows;
      total.value = tableData.value.length;
      console.log("tableData.value: ", tableData.value);
    });
  };
  
  // 获取组织数据
  const getDepartments = () => {
    StaffAPi.getdepartment().then((res: any) => {
      console.log(res);
      console.log("res.data.data: ", res.data.data);
      options1.value = buildMenu(res.data.data);
      options.value = buildMenu(res.data.data);
      console.log("options1.value/options.value: ", options1.value);
    });
  };
  
  const role = ref([]);
  const rolelist = () => {
    StaffAPi.getrole().then((res) => {
      console.log(res);
      role.value = res.data.data;
    });
  };
  
  // 获取数据
  onMounted(() => {
    getData();
    getDepartments();
    rolelist();
  });
  
  interface Tree {
    [key: string]: any;
  }
  
  const defaultProps = {
    children: "children",
    label: "name",
  };
  const defaultProps1 = {
    children: "children",
    label: "name",
    value: "id",
  };
  
  const search = ref("");
  const filterTableData = computed(() =>
    tableData.value.filter(
      (data) =>
        !search.value ||
        data.username.toLowerCase().includes(search.value.toLowerCase())
    )
  );
  
  // 树形图的数据
  
  // 导入导出
  const exportExcel = () => {
    // 创建工作簿
    const workbook = new ExcelJS.Workbook();
    // 添加工作表，名为sheet1
    const sheet1 = workbook.addWorksheet("sheet1");
    // 导出数据列表
    const data = tableData.value;
    // 获取表头所有键
    const headers = Object.keys(data[0]);
    // 将标题写入第一行
    sheet1.addRow(headers);
    // 将数据写入工作表
    data.forEach((row) => {
      const values = Object.values(row);
      sheet1.addRow(values);
    });
    // 导出表格文件
    workbook.xlsx
      .writeBuffer()
      .then((buffer) => {
        let file = new Blob([buffer], { type: "application/octet-stream" });
        FileSaver.saveAs(file, "ExcelJS.xlsx");
      })
      .catch((error) => console.log("Error writing excel export", error));
  };
  
  const uploadDialogVisible = ref(false);
  // 点击导入excel按钮事件
  const importExcel = () => {
    uploadDialogVisible.value = true;
  };
  // 文件数据
  const uploadData = ref([]);
  // 文件上传事件
  const datalist = ref([]);
  const handleChange = (file) => {
    const reader = new FileReader();
    reader.onload = () => {
      const content = reader.result;
      importFile(content)
        .then((data) => {
          console.log(data);
          tableData.value = [...tableData.value, ...data];
          console.log("datalist.value: ", tableData.value);
          uploadData.value = data;
        })
        .catch((response) => {
          //发生错误时执行的代码
          console.log(response);
          ElMessage.error("获取列表数据失败！");
        });
    };
    reader.readAsBinaryString(file.raw);
  };
  // 点击导入excel提交数据事件
  const submitUpload = () => {
    uploadDialogVisible.value = false;
  };
  
  // 角色
  const roledis = ref(false);
  const formLabelWidth = "140px";
  const rolex = () => {
    console.log(from.value);
    // StaffAPi.putDeptRoles(roleId.value)
    // role.value = false
  };
  const form = ref({
    checkList: [],
  });
  const roleFrom = ref([]);
  
  const detail = ref(false);
  const title = ref("");
  const detailForm = ref({
    title: "",
    phone: null,
    bumen: null,
    pinyong: null,
    stateTime: "",
    endTime: "",
    img: "",
  });
  
  interface RuleForm {
    username: string;
    mobile: string;
    formOfEmployment: number;
    departmentId: number;
    workNumber: string;
    timeOfEntry: string;
    correctionTime: string;
    staffPhoto: string;
  }
  
  const formSize = ref<ComponentSize>("default");
  const ruleFormRef = ref<FormInstance>();
  const ruleForm = ref<RuleForm>({
    username: "",
    mobile: "",
    formOfEmployment: 1,
    workNumber: "",
    departmentId: "",
    timeOfEntry: "",
    correctionTime: "",
    staffPhoto: "",
  });
  
  const rules = ref<FormRules<RuleForm>>({
    username: [
      { required: true, message: "Please input Activity name", trigger: "blur" },
      { min: 1, max: 4, message: "Length should be 3 to 5", trigger: "blur" },
    ],
    mobile: [
      { required: true, message: "Please input Activity name", trigger: "blur" },
    ],
    formOfEmployment: [
      {
        required: true,
        message: "Please select Activity count",
        trigger: "change",
      },
    ],
    workNumber: [
      { required: true, message: "Please input Activity name", trigger: "blur" },
    ],
    departmentId: [
      {
        required: true,
        message: "Please select Activity count",
        trigger: "change",
      },
    ],
    timeOfEntry: [
      {
        type: "date",
        required: true,
        message: "Please pick a date",
        trigger: "change",
      },
    ],
    correctionTime: [
      {
        type: "date",
        required: true,
        message: "Please pick a date",
        trigger: "change",
      },
    ],
  });
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid: any, fields: any) => {
      if (valid) {
        console.log(ruleForm.value);
        console.log("submit!");
        StaffAPi.putdept(ruleForm.value.id, ruleForm.value).then((res) => {
          console.log(res);
          // ElMessage.success("修改成功！");
          getData();
        });
        getData();
        detail.value = false;
      } else {
        console.log("error submit!", fields);
      }
    });
  };
  
  const submitFormAdd = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid: any, fields: any) => {
      if (valid) {
        console.log("submit!");
        ruleForm.value.departmentId = optionsId.value;
        // ruleForm.value.formOfEmployment=optionsId.value
        ruleForm.value.workNumber = "HEIMA0000" + tableData.value.length;
        ruleForm.value.id = tableData.value.length;
        console.log(ruleForm.value);
        StaffAPi.postdept(ruleForm.value).then((res) => {
          console.log(res);
          // ElMessage.success("添加成功！");
          getData();
        });
        getData();
        detail.value = false;
      } else {
        console.log("error submit!", fields);
      }
    });
  };
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    detail.value = false;
  };
  
  // 图片上传
  import { Plus } from "@element-plus/icons-vue";
  
  const imageUrl = ref("");
  let uploadfile2 = async (files) => {
    let filesObj = files.raw;
    // 创建 FileReader 对象
    const reader = new FileReader();
    // 当读取完成时触发
    reader.onload = () => {
      // 将图片转换为 Base64 字符串并赋值给 imageUrl.value
      imageUrl.value = reader.result as string;
      ruleForm.value.staffPhoto = reader.result as string;
    };
    reader.readAsDataURL(filesObj);
  };
  
  // 角色
  const dialogVisibles = ref(false); //角色弹窗
  const AllData = ref([]); //角色数据
  const roleId = ref(1); //临时存储的id
  const checkList = ref([]); //选择的选项
  const rolehandleEdit = async (obj: object) => {
    // roleId.value = obj.id
    console.log(obj);
  
    let { data } = (await getEnableRoleList()).data; //获取全部的角色
    console.log(data, "111");
  
    let roleObj = (await alertEnabled(obj.id)).data.roleIds; //获取当前员工分配的角色
    console.log(roleObj, "data");
    checkList.value = roleObj; //分配角色回显
    AllData.value = data;
    dialogVisibles.value = true;
  };
  
  // 角色弹窗
  // 关闭
  const handleClose = () => {
    dialogVisibles.value = false;
  };
  // 确定
  const roleOK = async () => {
    let arr = Object.values(checkList.value); //转换数组
    let obj = {
      id: roleId.value,
      roleIds: arr,
    };
    alertEnabled(obj);
    console.log(obj);
    // showMessage('角色分配成功')
    dialogVisibles.value = false;
    // let roleObj = (await getAlertEnabled(roleId.value)).data.permIds//获取当前员工分配的角色
    // console.log(roleObj, 1);
  };
  //选择
  const multipleTableRef = ref<InstanceType<typeof ElTable>>();
  const multipleSelection = ref<User[]>([]); //选择的数据
  const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val;
  };
  // 群发通知
  const notice: boolean = ref(false); //通知弹窗显示隐藏
  const inputValue = ref("");
  const dynamicTags = ref([]);
  const messagedj = ref("1"); //信息等级
  const content: string = ref(""); //通知内容
  // 打开通知弹窗
  const allNotice = () => {
    if (multipleSelection.value.length == 0) {
      showMessage("至少选择一个员工", "error");
    } else {
      notice.value = true;
      // 同步数据
      multipleSelection.value.forEach((item) => {
        dynamicTags.value.push({ name: item.username, id: item.id });
      });
      console.log(inputValue.value, dynamicTags.value);
    }
  };
  // 取消选项
  const noticeClose = (tag: string) => {
    let index = dynamicTags.value.indexOf(tag);
    dynamicTags.value.splice(index, 1);
    if (dynamicTags.value.length == 0) {
      noticeNo();
      showMessage("选项已清空，弹窗自动关闭!", "warning");
    }
  };
  
  // 取消
  const noticeNo = () => {
    notice.value = false;
    dynamicTags.value = []; //选项清空
    content.value = ""; //内容清空
  };
  // 确定
  const noticeOK = () => {
    notice.value = false;
    let rules = /^.{5,100}$/;
    if (rules.test(content.value)) {
      // 获取id
      let idArr = [];
      dynamicTags.value.forEach((item) => {
        idArr.push(item.id);
      });
      getNotice({
        content: content.value,
        type: messagedj.value,
        userIds: idArr,
      });
      showMessage("群发消息成功");
    }
    dynamicTags.value = []; //选项清空
    content.value = ""; //内容清空
  };
  
  let ida = ref(1) //点击的部门id
  const handleNodeClick = (data: any) => {
      console.log(data)
      ida.value = data.id
      getData()
  }
  </script>
  
  <style scoped lang="scss">
  .staff {
    width: 100%;
    height: 100%;
    display: flex;
  
    .staff-left {
      width: 190px;
      height: 100%;
      border-right: 1px solid rgb(145, 147, 153);
      padding: 10px;
    }
  
    .staff-right {
      flex: 1;
      height: 100%;
      padding: 10px;
    }
  }
  
  .demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
  }
  
  .demo-pagination-block .demonstration {
    margin-bottom: 16px;
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>
  